#!/usr/bin/env python

# pyspiderlint
#
# http://code.google.com/p/js-ria-tools/
# 
# This script reads a JavaScript file and sends it to spiderlint
# 
# Written by Steven Kollars
# 
# Copyright (c) 2008 Rackspace (www.rackspace.com)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy 
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights 
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
# copies of the Software, and to permit persons to whom the Software is 
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in 
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#

import os
import sys
import getopt
    
def usage():
    print """\
Usage: 
 spiderlint <file1.js> <file2.js> ... <fileN.js>
  
This script reads a JavaScript file sends it to spiderlint
"""

def main():
    try:
        opts, args = getopt.getopt(
                sys.argv[1:], "", [])
    except getopt.GetoptError:
        usage()
        sys.exit(2)
    
    path = os.getcwd()
    if len(args) > 0:
        sources = args[0:]
    else:
        usage()
        sys.exit(2)
    
    for source in sources:
        try:
            sf = open(source)
            try:
                js_data = sf.read()
            finally:
                sf.close()
        except IOError:
            print "Couldn't open file %s" % source
            continue
            
        temp_file = "spiderlint.temp"
        escaped_data = js_data.\
            replace('\\', r'\\').\
            replace("\r", "").\
            replace("\n", r"\n").\
            replace(r'"', r'\"')
            
        try:
            tf = open(temp_file, 'w')
            try:
                tf.write("var lint_source = \"%s\";" % escaped_data)
            finally:
                tf.close()
        except IOError:
            print "Couldn't create temporary file %s" % temp_file
            continue
        
        cmd = "spiderlintjs %s %s" % (source, temp_file)
        print os.popen(cmd).read()
        
        os.remove(temp_file)

if __name__ == "__main__":
    main()
    
